﻿<!--
 * @Author: yubaolee <yubaolee@163.com> | ahfu~ <954478625@qq.com>
 * @Description: OpenAuth.Pro代码生成器自动生成
 * Copyright (c) 2025 by yubaolee | ahfu~ , All Rights Reserved.  
-->
<template>
  <div class="flex flex-column">
    <sticky>
      <div class="search-box">
        <el-input @keyup.enter="handleFilter" size="small" class="custom-input w-200" :placeholder="'名称'"
          v-model="listQuery.key"></el-input>
        <el-button size="small" class="custom-button filter-item" icon="el-icon-search"
          @click="handleFilter">搜索</el-button>
      </div>
      <permission-btn v-on:btn-event="onBtnClicked"></permission-btn>
    </sticky>
    <auth-table ref="mainTableRef" :select-type="'checkbox'" :table-fields="headerList" :data="list"
      :v-loading="listLoading" @row-click="rowClick" @selection-change="handleSelectionChange"></auth-table>
    <el-pagination v-show="total > 0" :total="total" v-model:currentPage="listQuery.page"
      v-model:page-size="listQuery.limit" @current-change="handleCurrentChange" />
  </div>
  <el-dialog draggable class="dialog-mini" width="500px" :title="dialogStatus==0?'新增':'编辑'" v-model="dialogFormVisible">
    <auth-form ref="dataFormRef" :rules="rules" :edit-model="true" :form-fields="headerList" :data="temp"
      :col-num="2"></auth-form>
    <template v-slot:footer>
      <div>
        <el-button size="small" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button size="small" v-if="dialogStatus == 0" type="primary" @click="createData">
          确认
        </el-button>
        <el-button size="small" v-else type="primary" @click="updateData">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
//引入核心框架
import { ElMessage, ElNotification } from 'element-plus'
import { onMounted, ref, reactive, nextTick } from 'vue'
//引入API，共用方法
import * as {TableName}s from '@/api/{TableName}s'
import { defaultVal } from '@/utils/index'
import { delrows } from '@/utils/delRows.js'
import ColumnDefine from '@/interface/columnDefine'
//引入组件
import Sticky from '@/components/Sticky/index.vue'
import permissionBtn from '@/components/PermissionBtn/index.vue'
import AuthForm from '../../components/Base/AuthForm.vue'
import AuthTable from '../../components/Base/AuthTable.vue'
const headerList = ref([]) //列表头
const multipleSelection = ref([]) //列表checkbox选中的值
const list = ref([]) //列表值
const total = ref(0) //总条数
const listLoading = ref(true) //进度条
const dialogFormVisible = ref(false) //是否显示编辑框
const dialogStatus = ref(0) //0:新增 1:编辑
let temp = reactive({}) //新增（编辑）绑定对话框
const listQuery = reactive({
  // 查询条件
  page: 1,
  limit: 20,
  key: undefined,
})
const rules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
})
//组件refs
const mainTableRef = ref(null)
const dataFormRef = ref(null)
onMounted(() => {
  headerList.value = [
  {HeaderList}
  ]
  getList()
})
const rowClick = function (row) {
  mainTableRef.value.clearSelection()
  mainTableRef.value.toggleRowSelection(row)
}
const handleSelectionChange = function (val) {
  multipleSelection.value = val
}
const onBtnClicked = function (domId, callback) {
  switch (domId) {
    case 'btnAdd':
      handleCreate()
      break
    case 'btnEdit':
      if (multipleSelection.value.length !== 1) {
        ElMessage.error('只能选中一个进行编辑')
        return
      }
      handleUpdate(multipleSelection.value[0])
      break
    case 'btnDel':
      if (multipleSelection.value.length < 1) {
        ElMessage.error('至少删除一个')
        return
      }
      handleDelete(multipleSelection.value)
      break
    default:
      break
  }
}
const getList = function () {
  listLoading.value = true
  {TableName}s.getList(listQuery).then(response => {
    list.value = response.data
    response.columnFields.forEach(item => {
      // 首字母小写
      item.columnName =
        item.columnName.substring(0, 1).toLowerCase() +
        item.columnName.substring(1)
    })
    headerList.value = response.columnFields
    total.value = response.count
    listLoading.value = false
  })
}
const handleFilter = function () {
  listQuery.page = 1
  getList()
}

const handleCurrentChange = function (val) {
  listQuery.page = val
  getList()
}

const resetTemp = function () {
  let obj = {}
  headerList.value.forEach(item => {
    obj[item.columnName] = defaultVal(item.entityType)
  })
  Object.assign(temp, obj)
}
const handleCreate = async function () {
  resetTemp()
  dialogStatus.value = 0
  dialogFormVisible.value = true
  await nextTick()
  dataFormRef.value.clearValidate()
}
const createData = function () {
  dataFormRef.value.validate(() => {
    {TableName}s.add(temp).then(() => {
      list.value.unshift(temp)
      dialogFormVisible.value = false
      ElNotification.success('创建成功')
    })
  })
}
const handleUpdate = async function (row) {
  Object.assign(temp, row) //必需这样赋值才能响应式
  dialogStatus.value = 1
  dialogFormVisible.value = true
  await nextTick()
  dataFormRef.value.clearValidate()
}
const updateData = function () {
  dataFormRef.value.validate(() => {
    const tempData = Object.assign({}, temp)
    {TableName}s.update(tempData).then(() => {
      for (const v of list.value) {
        if (v.id === temp.id) {
          const index = list.value.indexOf(v)
          list.value.splice(index, 1, temp)
          break
        }
      }
      dialogFormVisible.value = false
      ElNotification.success('更新成功')
    })
  })
}
const handleDelete = function (rows) {
  delrows({TableName}s, rows, getList)
}
</script>
